<?php
function buildInsertQuery($table, array $row )
{
	$fields = "";
	$values ="";
	
	foreach( $row as $k => $v )
	{
		$row[$k] = "'".$v."'";
	}
	
	$fields = implode( ', ', array_keys( $row ) );
	$values = implode( ', ', array_values( $row ) );
	
	$query = "INSERT INTO {$table} ({$fields}) VALUES ({$values})";
	
	return $query;
}

function languages( $key = null )
{
	$languages = array(
		'vietnam' => 'Vietnamese',
		'english' => 'English',
		'france' => 'France'
	);
	
	if( $key != null )
	{
		return $languages[$key];
	}
	return $languages;
}

function curlRequest( $url, array $fields, $postMethod = false )
{
	$fields_string = '';
	foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
	rtrim($fields_string,'&');
	
	//open connection
	$ch = curl_init();
	
	//set the url, number of POST vars, POST data
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
	
	//execute post
	$result = curl_exec($ch);
	
	//close connection
	curl_close($ch);
	
	return $result;
}


function detectLanguage( $text )
{
	$API_KEY = '7d9d1988aa8ec0f9ae6b58c2e76d3abc'; //TODO this should be in config file
	$API_URL = 'http://ws.detectlanguage.com/0.2/detect';

	$response = curlRequest( $API_URL, array('q' => $text , 'key' => $API_KEY ) );
	$responseArray = json_decode( $response, true );

	//Get reliable true or mx confident record
	return isset( $responseArray['data']['detections'][0]['language'] )  ? $responseArray['data']['detections'][0]['language'] : '';
}

?>